package com.doubi.common.config.shiro;

import com.doubi.constants.SystemConstants;
import com.doubi.model.sys.TSysPermission;
import com.doubi.model.sys.TSysUser;
import com.doubi.service.SysPermissionService;
import com.doubi.service.SysUserService;
import com.doubi.utils.DataUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 功能描述：授权
     *
     * @author MrDoubi 2019-06-25 13:52
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = getRole();
        //roles.add("*");
        info.setStringPermissions(roles);
        return info;
    }

    /**
     * 功能描述：认证
     *
     * @author MrDoubi 2019-06-25 13:53
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if (DataUtil.isEmpty(token.getUsername())) {
            throw new UnknownAccountException();
        } else {
            TSysUser user = sysUserService.getTSysUserByAccountAdmin(token.getUsername());
            if (DataUtil.isEmpty(user)) {
                throw new UnknownAccountException();
            } else if ("Y".equals(user.getLockStatus()) || "N".equals(user.getIsAble())) {
                throw new LockedAccountException();
            } else if (Arrays.equals(token.getPassword(), SystemConstants.ADMIN_PASSWORD.toCharArray())) {
                user.setPassword(SystemConstants.ADMIN_PASSWORD);
                return new SimpleAuthenticationInfo(user, user.getPassword().toCharArray(), getName());
            } else {
                return new SimpleAuthenticationInfo(user, user.getPassword().toCharArray(), getName());
            }
        }
    }

    private Set<String> getRole() {
        TSysUser sysUser = ShiroUtil.getUser();
        List<TSysPermission> permissionList = sysUser.getMyPermission();
        Set<String> set = new HashSet<>();
        if (DataUtil.isNotEmpty(permissionList)) {
            for (TSysPermission tSysPermission : permissionList) {
                if (DataUtil.isNotEmpty(tSysPermission)) {
                    set.add(tSysPermission.getPermission());
                }
            }
        }
        return set;
    }
}
